package gw.com.android.greendao;

import android.database.sqlite.SQLiteDatabase;
import android.os.Looper;
import android.text.TextUtils;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2018-07-27.
 */
public class DaoHelper {

    private static DaoHelper instance;
    private static String mKey;
    private DaoSession daoSession;

    private DaoHelper(String key) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            throw new IllegalAccessError("ban to access database in main thread.");
        }
        String dbName = key + "_message.db";
        DaoMaster.DevOpenHelper openHelper = new MyOpenHelper(AppMain.getApp(), dbName);
        SQLiteDatabase database = openHelper.getWritableDatabase();
        DaoMaster master = new DaoMaster(database);
        daoSession = master.newSession();
    }

    public static synchronized DaoHelper getInstance() {
        String mCurName = GTConfig.instance().mCurName;
        if (TextUtils.isEmpty(mCurName)) {
            if (!TextUtils.isEmpty(mKey)) {
                mKey = null;
                instance = null;
            }
            if (instance == null) {
                instance = new DaoHelper("guest");
                Logger.i("_notify", "create daohelper : guest");
            }
            return instance;
        } else {
            if (!mCurName.equals(mKey)) {
                mKey = mCurName;
                instance = null;
            }
            if (instance == null) {
                instance = new DaoHelper(mKey);
                Logger.i("_notify", "create daohelper : " + mKey);
            }
        }
        return instance;
    }

    public NotifyDataDao getNotifyDataDao() {
        return daoSession.getNotifyDataDao();
    }

}
